<template>
    <div class="realtimestatus">
        <div class="swich">
            <div class="demo-input-suffix">状态筛选：</div>
            <div class="demo-input-suffix" style="margin-left:5px;margin-right:15px;height:38px" >
            <el-select v-model="select_direct" placeholder="全部" @change="loadAllBoxs">
                <el-option
                    v-for="item in tableDatatype"
                    :key="item.id"
                    :label="item.NAME"
                    :value="item.NAME"
                ></el-option>
            </el-select>
            </div>
            <el-checkbox v-model="checkedshowThrowInfo" @change="showThrowInfo" style="margin-top:5px;">显示投放信息</el-checkbox>
            <el-button class="historythrowinfo" @click="showhistorythrow" >历史投放记录</el-button>
            <el-button class="historythrowinfo" @click="showhistorythrow" >历史投放记录</el-button>
            
            <el-dialog class="historydialog" :visible.sync="menuRoleVisible" append-to-body>
              <person-management ref="usermanage"/>
            </el-dialog>
            <!-- <input type="text" name="" id="" placeholder=> <menu-role v-if="menuRoleVisible" ref="PersonManagement"></menu-role>-->
        </div>
        <div class="baidumap" id="allmap" style="position: relative"></div>
        <div class="shouxx" id="shouxx"></div>
        <div class="m_tableContent m_gasMonitoring" @click="handleClick($event)">
        <div class='table_head'>
          <ul class="ulName">
            <li class="liNameMax">行政区</li>
            <li class="liName">街道</li>
            <li class="liName">社区</li>
            <li class="liName">小区</li>
            <li class="liName">桶站名</li>
            <li class="liName">违规时间</li>
            <li class="liNameMax">违规类型</li>
          </ul>
        </div>
        <vue-seamless-scroll v-if="tableDatabak.length>0" :data="tableData" class="seamless-warp" :class-option="classOption" style="height: 220px;padding-right: 10px;">
          <ul>
            <li class="DataList_top" v-for="(item,index) in tableData" :key="index">
              <div class="DataList_left">
                <ul class="ulName">
                  <li class="liNameMax">{{item.行政区}}</li>
                  <li class="liName">{{item.街道}}</li>
                  <li class="liName">{{item.社区}}</li>
                  <li class="liName">{{item.小区}}</li>
                  <li class="liName">{{item.桶站名}}</li>
                  <li class="liName">{{item.违规时间}}</li>
                  <li class="liNameMax">{{item.违规类型}}</li>
                </ul>
              </div>
              <div class="scrollline"></div>
            </li>
          </ul>
        </vue-seamless-scroll>
        </div>
    </div>
</template>
<script>
import Vue from 'vue';
import vueSeamlessScroll from 'vue-seamless-scroll'
import open from '@/assets/img/openimg.png'
import lajitong from '@/assets/img/closeimg.png'
import fill from '@/assets/img/fill.png'
import '../../assets/css/common.css'
import PersonManagement from '@/components/page/rubbishthrowhistory.vue'
import guideVue from './guide.vue'
import residentsmessageVue from './residentsmessage.vue'
import homeVue from '../personnel/home.vue'
import TabsVue from './Tabs.vue'
import TagsVue from '../common/Tags.vue'


export default{
  map: null,
  name: 'Bmap',
  markdate:null,
  components: {
    'person-management': PersonManagement,
    vueSeamlessScroll
  },
  computed: {
     classOption () {
       return {
        step: 0.4, // 数值越大速度滚动越快
        limitMoveNum: 1, // 开始无缝滚动的数据量 this.dataList.length
        hoverStop: true, // 是否开启鼠标悬停stop
        direction: 1, // 0向下 1向上 2向左 3向右
        openWatch: true , // 开启数据实时监控刷新dom
        singleHeight: 0, // 单步运动停止的高度(默认值0是无缝不停止的滚动) direction => 0/1
        singleWidth: 0, // 单步运动停止的宽度(默认值0是无缝不停止的滚动) direction => 2/3
        waitTime: 1000 // 单步运动停止的时间(默认值1000ms)
      }
    }
  },
  data () {
    return {
      select_direct: '',
      checkedshowThrowInfo: '',
            tableData: [],
            tableDatabak: [{
                date: '2020-08-18 09:54',
                name: '刘婧',
                address: '集贤里3号楼1门',
                box:'集贤里1号垃圾桶',
                weight:'567g',
                type:'可回收垃圾'
                }, {
                date: '2020-08-18 08:46',
                name: '王勇',
                address: '集贤里5号楼3门',
                box:'集贤里2号垃圾桶',
                weight:'482g',
                type:'可回收垃圾'
                }, {
                date: '2020-08-18 08:42',
                name: '张秀琳',
                address: '集贤里17号楼1门',
                box:'集贤里7号垃圾桶',
                weight:'350g',
                type:'可回收垃圾'
                }, {
                date: '2020-08-18 08:17',
                name: '刘静',
                address: '集贤里13号楼3门',
                box:'集贤里5号垃圾桶',
                weight:'476g',
                type:'可回收垃圾'
            }],
            tableDatatype: [{
                id: '0',
                NAME: '全部'
                },{
                id: '1',
                NAME: '关盖'
                }, {
                date: '2',
                NAME: '开盖'
                }, {
                date: '3',
                NAME: '溢满'
                }, {
                date: '4',
                NAME: '故障'
                }],
      websock: null,
      websockthrow: null,
      map: null,
      txt: '',
      label: '',
      myIcon:'',
      markers:[],
      peoplelist:[],
      menuRoleVisible : false
    }
  },
  mounted () {
    this.InitMap()
    this.getlistdata()
  },
  destroyed () {
    this.websock.close() 
  },
  methods: {
    initWebSocket () { 
      const wsuri = "ws://192.168.1.4:5576";
      this.websock = new WebSocket(wsuri);
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;

      // const wsurithrow = "ws://111.160.78.62:4463";
      // //const wsurithrow = "ws://192.168.1.120:9946";
      // this.websockthrow = new WebSocket(wsurithrow);
      // this.websockthrow.onmessage = this.websocketonmessagethrow;
      // this.websockthrow.onopen = this.websocketonopenthrow;
      // this.websockthrow.onerror = this.websocketonerrorthrow;
      // this.websockthrow.onclose = this.websocketclosethrow;
    },
    websocketonopen () { 
      let actions = { "test": "12345" };
      this.websocketsend(JSON.stringify(actions));
    },
    websocketonerror () {
      this.initWebSocket();
    },
    websocketonmessage (e) { 

     const redata = JSON.parse(e.data);
     var id = JSON.parse(redata).deviceID.toLowerCase();
     //id=248;
     var me = this;
     console.log(JSON.parse(redata).state == 0)
     console.log(JSON.parse(redata).data)
       if(JSON.parse(redata).data.state == 1){
         //alert('开盖');
         //alert('开盖'+id);
         this.myIcon = new BMap.Icon(open, new BMap.Size(48, 48));
         this.label = new BMap.Label(me.data[id].chargerMarker.getLabel().content.split(',')[0]+',开盖', { offset: new BMap.Size(40, -10) });
       }else if(JSON.parse(redata).data.full == 1){
         //alert('溢满');
         //alert('溢满'+id);
         this.myIcon = new BMap.Icon(fill, new BMap.Size(48, 48));
         this.label = new BMap.Label(me.data[id].chargerMarker.getLabel().content.split(',')[0]+',溢满', { offset: new BMap.Size(40, -10) });
       }else{
         //alert('关盖');
         //alert('关盖'+id);
         this.myIcon = new BMap.Icon(lajitong, new BMap.Size(48, 48));
         this.label = new BMap.Label(me.data[id].chargerMarker.getLabel().content.split(',')[0]+',关盖', { offset: new BMap.Size(40, -10) });
       }
      console.log(this.label,this.myIcon)
      //me.data[id].chargerMarker.setIcon(this.myIcon);
      //me.data[id].chargerMarker.setLabel(this.label);
      this.map.removeOverlay(me.data[id].chargerMarker.getLabel())
      me.data[id].chargerMarker.setIcon(this.myIcon);
      me.data[id].chargerMarker.setLabel(this.label);
    },
    websocketsend (Data) {
      this.websock.send(Data);
    },
    websocketclose (e) { 

    },

    websocketonopenthrow () { 
      let actions = { "test": "12345" };
      this.websocketsendthrow(JSON.stringify(actions));
    },
    websocketonerrorthrow () {
      this.initWebSocket();
    },
    websocketonmessagethrow (e) { 
      const redata = JSON.parse(e.data);
      var sn = JSON.parse(redata).deviceSN.toLowerCase();
      var ttime = JSON.parse(redata).throwTime.toLowerCase();
      var uid = JSON.parse(redata).UserID.toLowerCase();
      var tweight = JSON.parse(redata).TrashWeight.toLowerCase();
      var dtype = JSON.parse(redata).DoorType.toLowerCase();
      // this.peoplelist.data.forEach(item => {
      //   if(item.VID==uid){
      //     var tdata='{"date": "'+ttime+'","name": "'+item.NAME+'","address": "'+item.BUILDING+item.UNIT+'","weight":"'+tweight+'","type":"'+dtype+'"}';
      //     const redatat = JSON.parse(tdata);
      //     this.tableDatabak.push(redatat);
      //     this.tableData=this.tableDatabak;
      //   }
      // })
    },
    websocketsendthrow (Data) {
      this.websockthrow.send(Data);
    },
    websocketclosethrow (e) { 

    },

    InitMap () {
      // var City = '太原'
      // this.map = new BMap.Map('allmap')
      // var point = new BMap.Point(112.593887,37.866154) // 创建点坐标

      // var City = '北京'
      // this.map = new BMap.Map('allmap')
      // var point = new BMap.Point(116.404, 39.915) // 创建点坐标

      // var City = '福州'
      // this.map = new BMap.Map('allmap')
      // var point = new BMap.Point(117.011533,35.406814) // 创建点坐标.

      // var City = '邹城市'
      this.map = new BMap.Map('allmap')
      var point = new BMap.Point(117.011533,35.406814) // 创建点坐标

      this.map.centerAndZoom(point, 14) 
      this.map.enableScrollWheelZoom(true)

      this.map.addControl(new BMap.NavigationControl())
      this.map.addControl(new BMap.ScaleControl())
      this.map.addControl(new BMap.OverviewMapControl())
      this.map.addControl(new BMap.MapTypeControl())
      //alert(this.$url+ '/GetRubbishPointsApi?ClientNo=' + localStorage.getItem("clentno") + '&Level=' + localStorage.getItem("USERLEVEL"));
      this.$axios({
        //url: 'http://111.160.78.62:5575/GarbagePointsTYApi/BasicData/RubbishBoxApi?VillageNo=&PeopleID=',
        //url: 'http://111.160.78.62:5575/GarbagePointsTYApi/BasicData/RubbishBoxApi?VillageNo=&PeopleID=',
        url:  this.$url+ '/GetRubbishPointsApi?ClientNo=' + localStorage.getItem("clentno") + '&Level=' + localStorage.getItem("USERLEVEL"),
        //url:  'http://111.160.78.62:5575/GarbagePointsTYApi/BasicData/GetRubbishPointsApi?ClientNo=' + localStorage.getItem("clentno") + '&Level=' + localStorage.getItem("USERLEVEL"),
        method: 'get'
      }).then((res) => {
        this.showPoint(res);
      }).catch((error) => {

      })
      // this.tableData=this.tableDatabak;
    },

    getlistdata(){
      var me = this;
      // const startTime = this.$moment().subtract(31, 'day').format('YYYY-MM-DD');
      // const endTime = this.$moment().add(1,'day').format('YYYY-MM-DD');
      // var url = this.$aurl+ '/GetCollectMessagesWithApi?startTime='+startTime+'&endTime='+endTime+'&ClientNo=1&Level=行政区'
      var url = this.$iurl+ '/getVideoHistoryInfo?ClientNo=' + localStorage.getItem("clentno") + '&StreetNo=0&TimeInterval=300&type=1'
      this.$axios({
        url: url,
        method:'get'
      }).then(res=>{
        // res.data.forEach(item => {
        //   // 021/4/26 0:00:00","Recyclable":90.0,"Kitchen":0.0,"Harmful":0.0,"Other"
        //   if(item.Recyclable > 0){
        //     item.type = '可回收垃圾'
        //     item.weight = item.Recyclable
        //   }
        //   if(item.Kitchen > 0){
        //     item.type = '可回收垃圾1'
        //     item.weight = item.Kitchen
        //   }
        //   if(item.Harmful > 0){
        //     item.type = '可回收垃圾2'
        //     item.weight = item.Harmful
        //   }
        //   if(item.Other > 0){
        //     item.type = '可回收垃圾3'
        //     item.weight = item.Other
        //   }
        // })
        
        // res.data.forEach(element => {
        //   this.map.addOverlay(new BMap.Marker(new BMap.Point(element.经度, element.纬度)));
        // });
        this.tableData = res.data
      })
      // me.map.addOverlay(new BMap.Marker(new BMap.Point(112.547885,37.856838)));
      // me.map.centerAndZoom(new BMap.Point(112.547885,37.856838), 14)
    },
    baiduMap () {
      var map = new BMap.Map('allmap')
      map.addControl(new BMap.NavigationControl())
      map.addControl(new BMap.ScaleControl())
      map.addControl(new BMap.OverviewMapControl())
      map.addControl(new BMap.MapTypeControl())
      var point = new BMap.Point(117.19185, 39.090468) 
      map.centerAndZoom(point, 17)
      map.enableScrollWheelZoom(true) 
    },

    handleClick(event) {
      this.staffInfo.staffId = event.target.id
      this.staffInfo.staffName = event.target.name
      this.staffInfo.deptName = event.target.dataset.dept
      this.handlePhoneStaff()
    },
    
    async showPoint (data) {
      this.markers=[];
      this["data"] = {};
      var mcount='0';
      this.map.clearOverlays()
      data.data.forEach(item => {
        // debugger
        if(item.boxs.length>0&&item.boxs[0].DEVICE_ID!=null&&item.boxs[0].DEVICE_ID.length>4)
        this['data'][item.boxs[0].DEVICE_ID] = item
        else
        this['data'][item.ID] = item
        //if(mcount=='开盖'){
        //  mcount='溢满';
        //}else if(mcount=='溢满'){
        //  mcount='关盖';
        //}else{
        //  mcount='开盖';
        //}
        item.REMARK=mcount;
        this.addMark(item)
      })
      this.markdate=data;
    },

    addInfoWindow (marker,item) {
      var _this = this;
      marker.addEventListener("rightclick",  function () {
        
        _this.$axios({
          //url: 'http://111.160.78.62:5575/GarbagePointsTYApi/BasicData/GetRubbishBoxWeight?ID='+item.ID,
          url: this.$url+ '/GetRubbishBoxWeight?ID='+item.ID,
          method: 'get'
        }).then((res) => {
          res.data.forEach(itemnow => {
            if(item.ID==itemnow.ID){
              item.WEIGHT_CC=itemnow.LONGITUDE;
              item.WEIGHT_KHS=itemnow.WEIGHT_KHS;
              item.WEIGHT_QT=itemnow.WEIGHT_QT;
              item.WEIGHT_YH=itemnow.WEIGHT_YH;
            }

          })
        }).catch((error) => {

        })
        if(item.WEIGHT_CC==null){item.WEIGHT_CC='0';}
        if(item.WEIGHT_KHS==null||item.WEIGHT_KHS.length<1){item.WEIGHT_KHS='0';}
        if(item.WEIGHT_QT==null){item.WEIGHT_QT='0';}
        if(item.WEIGHT_YH==null){item.WEIGHT_YH='0';}
        if(item.PEOPLE_NAME==null){item.PEOPLE_NAME='无';}
        if(item.LOCATION==null){item.LOCATION='无';}
        if(item.TYPE_NAME==null){item.TYPE_NAME='垃圾类型';}
        if(item.WEIGHT==null){item.WEIGHT='无';}
        if(item.WEIGHT_TIME==null){item.WEIGHT_TIME='无';}
        var sContent = '<iframe src="../../infowindow.html" width=400 height=220 frameborder=0 scrolling=no></iframe>'
          + "<p style='margin:0;line-height:1.5;font-size:17px;text-indent:1em'>厨余垃圾桶："+item.WEIGHT_CC+"kg</p>"
          + "<p style='margin:0;line-height:1.5;font-size:17px;text-indent:1em'>可回收圾桶："+item.WEIGHT_KHS+"kg</p>"
          + "<p style='margin:0;line-height:1.5;font-size:17px;text-indent:1em'>其他垃圾桶："+item.WEIGHT_QT+"kg</p>"
          + "<p style='margin:0;line-height:1.5;font-size:17px;text-indent:1em'>有害垃圾桶："+item.WEIGHT_YH+"kg</p>"
          + "<br>"
          + "<p style='margin:0;line-height:1.5;font-size:17px;text-indent:1em'>最后一次投放记录</p>"
          + "<p style='margin:0;line-height:1.5;font-size:17px;text-indent:1em'>户主："+item.PEOPLE_NAME+"</p>"
          + "<p style='margin:0;line-height:1.5;font-size:17px;text-indent:1em'>户号："+item.LOCATION+"</p>"
          + "<p style='margin:0;line-height:1.5;font-size:17px;text-indent:1em'>"+item.TYPE_NAME+"："+item.WEIGHT+"g</p>"
          + "<p style='margin:0;line-height:1.5;font-size:17px;text-indent:1em'>时间："+item.WEIGHT_TIME+"</p>"
          + "<br>"
          + "<p style='margin:0;line-height:1.5;font-size:17px;text-indent:1em'>指导员：张旭</p>";
        
        var infoWindow = new BMap.InfoWindow(sContent, { width: 400, height: 400 });  // 创建信息窗口对象
        this.openInfoWindow(infoWindow);
      });
    },
    
    addMark (data) {
      var me = this;
      var label;
      var myPoint = new BMap.Point(),
		    htmlWidth = document.documentElement.getBoundingClientRect().width,
		    MapSize = (20 * (htmlWidth / 750));
      var point = new BMap.Point(data.LONGITUDE, data.LATITUDE); 
      var marker;  
      if(data.REMARK=='开盖'){
        marker = new BMap.Marker(point, { icon: new BMap.Icon(open, new BMap.Size(MapSize, MapSize)) });  
      }else if(data.REMARK=='溢满'){
        marker = new BMap.Marker(point, { icon: new BMap.Icon(fill, new BMap.Size(MapSize, MapSize)) });  
      }else{
        marker = new BMap.Marker(point, { icon: new BMap.Icon(lajitong, new BMap.Size(MapSize, MapSize)) });  
      }
      label = new BMap.Label('垃圾桶'+data.ID, { offset: new BMap.Size(40, -10) }); 
      marker.setLabel(label);  
      marker.setTitle(data.ID); 
      marker.className = 'rubbishbox';
      this.markers.push(marker);
      this.addInfoWindow(marker,data);
      me.map.addOverlay(marker);  
      data["chargerMarker"] = marker; 
    },
    loadAllBoxs(value) {
      this.markers=[];
      this.checkedshowThrowInfo=false;
      this.map.clearOverlays()
      this.markdate.data.forEach(item => {
        if(value=="全部"){
          this.addMark(item)
        }
        if(item.REMARK==value){
          this.addMark(item)
        }
      })
    },
    showThrowInfo: function(e,checkedshowThrowInfo){

      this.$axios({
        //url: 'http://111.160.78.62:5575/GarbagePointsTYApi/BasicData/RubbishBoxApi?VillageNo=&PeopleID=',
        //url: 'http://111.160.78.62:5575/GarbagePointsTYApi/BasicData/RubbishBoxApi?VillageNo=&PeopleID=',
        url:  this.$url+ '/GetRubbishPointsApi?ClientNo=' + localStorage.getItem("clentno") + '&Level=' + localStorage.getItem("USERLEVEL"),
        method: 'get'
      }).then((res) => {
        var label;
        for (var i = 0; i < this.markers.length; i++) {
          var marker = this.markers[i]
          if (this.checkedshowThrowInfo) {
            res.data.forEach(item => {
                if(marker.getTitle()==item.ID){
                  if(item.WEIGHT_CC==null){item.WEIGHT_CC='0';}
                  if(item.WEIGHT_KHS==null||item.WEIGHT_KHS.length<1){item.WEIGHT_KHS='0';}
                  if(item.WEIGHT_QT==null){item.WEIGHT_QT='0';}
                  if(item.WEIGHT_YH==null){item.WEIGHT_YH='0';}
                  label = new BMap.Label(marker.getLabel().content+"<br />总计100公斤<br />厨余"+item.WEIGHT_CC+"公斤<br />可回收10公斤<br />其他5公斤<br />有害5公斤", { offset: new BMap.Size(40, -10) }); 
                  this.map.removeOverlay(marker.getLabel())
                  marker.setLabel(label);
                }
            })
            //this.addInfoWindowinfo(marker);
          } else {
            label = new BMap.Label(marker.getLabel().content.split('<br />')[0], { offset: new BMap.Size(40, -10) }); 
            this.map.removeOverlay(marker.getLabel())
            marker.setLabel(label);
          }
        }  
      }).catch((error) => {

      })


    },

    showhistorythrow: function(e){
      let roleId = e;
      this.menuRoleVisible = true;
      this.$nextTick(()=>{
            this.$refs.usermanage.personManageout(roleId)
       })
    },

    addInfoWindowinfo (marker) {
      var opts = {    
      width : 250,     // 信息窗口宽度    
      height: 100,     // 信息窗口高度    
      title : "Hello"  // 信息窗口标题   
      }    
      var infoWindow = new BMap.InfoWindow("World", opts);  // 创建信息窗口对象    
      this.map.openInfoWindow(infoWindow, map.getCenter());
    },
  }
}
</script>
<style scoped>
.realtimestatus,body{
       width: 100%;
       height: 100%;
       position: relative;
       box-sizing: border-box;
}
.baidumap {
    width: 100%;
    height: 95%;
    border: 2px solid #9A9A9A;
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
  }
.baidumap > .BMap_cpyCtrl {
    display: none !important;
}
.baidumap > .anchorBL {
    display: none !important;
}
.table_head{
       font-size: 15px;
       position:absolute;
       right: 10px;
       bottom: 225px;
       z-index: 555;
       width: 1000px;
       height: 40px;
       opacity: 0.9;
       background: #e1e1e1;
       list-style: none;
       display: inline-block;
       padding-top: 7px;
   }
.ulName{
  display:inline;
  white-space:nowrap;
  text-align: center;
}
.liName{
  list-style: none;
  display: inline-block;
  width: 12%;
}
.liNameMin{
  list-style: none;
  display: inline-block;
  width: 15%;
}
.liNameMax{
  list-style: none;
  display: inline-block;
  width: 20%;
}
.seamless-warp{
       font-size: 15px;
       position:absolute;
       right: 10px;
       bottom: 5px;
       z-index: 555;
       width: 1000px;
       overflow: hidden;
       background: #e1e1e1;
}
.scrollline{
       width: 1000px;
       height: 1px;  
       background: #0000f1;
       margin-top: 10px;
       margin-bottom: 10px;
       }
.demo-input-suffix {
    float: left;
    font-size: 15px;
    height: 32px;
    line-height: 32px;
    padding-bottom: 5px;
}
.historythrowinfo{
  margin-left: 15px;
}
.historydialog{
  width: 100%;
}
</style>




